import 'package:flutter_cache_manager/file.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:love_newf/app/com/http/http_request.dart';
import 'package:love_newf/app/com/model/room_prop_model.dart';
import 'package:love_newf/app/com/util/my_toast.dart';

import '../base/L.dart';

class GiftUtils {
  static const key = 'customCacheKey';
  static CacheManager instance = CacheManager(
    Config(
      key,
      stalePeriod: const Duration(days: 365 * 100),
      maxNrOfCacheObjects: 20,
      repo: JsonCacheInfoRepository(databaseName: key),
      // fileSystem: IOFileSystem(key),
      fileService: HttpFileService(),
    ),
  );

  static List<RoomPropModel> _roomPropList = [];
  static Map<int, RoomPropModel> _roomPropMaps = {};
  static var refreshList = false;

  static get roomPropList async {
    if (L.loginUserInfo?.saToken == null) {
      return [];
    }
    if (_roomPropList.isEmpty || refreshList) {
      var list = await HttpRequest().postList<RoomPropModel>(
          "/api/prop/getRoomProp", {},
          loadingText: "加载中...");
      if (list != null) {
        _roomPropList = list;
        for (var model in _roomPropList) {
          _roomPropMaps[model.id] = model;
        }
      }
    }
    return _roomPropList;
  }

  static String propName(id) {
    return _roomPropMaps[id]?.name ?? "";
  }

  static String getPropPrice(id) {
    return _roomPropMaps[id]?.rosePrice.toString() ?? "";
  }

  static RoomPropModel? getProp(id) {
    return _roomPropMaps[id];
  }
  static Future<RoomPropModel?> getPropAsync(id) async{
    var model = _roomPropMaps[id];
    if (model == null) {
      refreshList = true;
      await roomPropList;
      model = _roomPropMaps[id];
      if (model == null) {
        toastError("没有这个礼物：$id");
        return null;
      }

    }
    return model;
  }

  static Future<File?> getEffectFile(int id) async {
    var model = _roomPropMaps[id];
    if (model == null) {
      refreshList = true;
      await roomPropList;
      model = _roomPropMaps[id];
      if (model == null) {
        toastError("没有这个礼物：$id");
        return null;
      }
    }
    if (!model.effectUrl.contains("/")) return null;
    String name = model.effectUrl.substring(model.effectUrl.lastIndexOf("/"));
    var file =
        await DefaultCacheManager().getSingleFile(model.effectUrl);//, key: name
    return file;
  }
}
